package com.tobeface.sns.interfaces.util;

import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.apache.commons.lang.StringUtils;

import com.kissme.lang.Preconditions;
import com.tobeface.sns.interfaces.exception.InvalidCaptchaException;

/**
 * 
 * @author loudyn
 * 
 */
public final class HttpCaptchaHelper {

	private static final String MUST_VALIDATE_CPATCHA_ATTR = "com.sinzv.sns.must-validate-captcha";
	private static final String CAPTCHA_ATTR = "com.sinzv.sns.captcha";

	/**
	 * 
	 * @param captchaString
	 * @param session
	 */
	public static void checkCaptcha(String captchaString, HttpSession session) {

		Preconditions.notNull(session, new InvalidCaptchaException("None session!"));

		if (!isMustValidateCaptcha(session)) {
			return;
		}

		// check chaptchaString first,if we not,when call captcha.isCorrect() it may occur NullPointException
		if (StringUtils.isBlank(captchaString)) {
			throw new InvalidCaptchaException("Blank captcha!");
		}

		Captcha captcha = (Captcha) session.getAttribute(CAPTCHA_ATTR);
		if (null == captcha || !captcha.isCorrect(captchaString)) {
			throw new InvalidCaptchaException("Wrong captcha!");
		}
	}

	private static boolean isMustValidateCaptcha(HttpSession session) {
		Boolean mustValidateCaptcha = (Boolean) session.getAttribute(MUST_VALIDATE_CPATCHA_ATTR);
		return null != mustValidateCaptcha && mustValidateCaptcha;
	}

	/**
	 * 
	 * @param captcha
	 * @param session
	 */
	public static void storeCaptcha(Captcha captcha, HttpSession session) {
		mustValidate(session);
		session.setAttribute(CAPTCHA_ATTR, captcha);
	}

	/**
	 * 
	 * @param session
	 */
	public static void mustValidate(HttpSession session) {
		session.setAttribute(MUST_VALIDATE_CPATCHA_ATTR, Boolean.TRUE);
	}

	private HttpCaptchaHelper() {}
}
